//
//  MapViewController.m
//  FiltrationSystem
//
//  Created by 123456 on 2017/1/23.
//  Copyright © 2017年 YTYangK. All rights reserved.
//

#import "MapViewController.h"
//显示地图
#import <MapKit/MapKit.h>
//定位
#import <CoreLocation/CoreLocation.h>
#import "KCAnnotation.h"
#import "MapViewModel.h"
#import "RightViewModel.h"
#import "NavigationView.h"
#import "RightView.h"
#import "JZLocationConverter.h"

@interface MapViewController ()<CLLocationManagerDelegate,MKMapViewDelegate>
{
//    CLLocationManager *_locationManager;
    KCAnnotation *annotation1;//大头针
    UIView *MaskView;//遮罩层
    NSDictionary* parameterDic;
    NavigationView *Nview;//导航头
    RightView *Rview;//侧滑
    BOOL _firstDisplay; //是否第一loading
    
    double latitude;
    double longitude;
    
    NSString *latitude1;
    NSString *longitude1;
}

@property (weak, nonatomic) IBOutlet MKMapView *_mapView;
@property (nonatomic,strong) CLGeocoder *geocoder;
@property (nonatomic,strong)NSMutableArray *AnnotationAry;

@end

@implementation MapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self updateUI];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self deleteAll];
    [self requestURLwithViewForMap];
    
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    _firstDisplay=NO;
}


-(void)updateUI{

    self.title = @"地图";
    _firstDisplay = YES;
    //设置代理
    self._mapView.delegate=self;
    
    //请求定位服务
//    _locationManager=[[CLLocationManager alloc]init];
//    _locationManager.delegate = self;
//    if(![CLLocationManager locationServicesEnabled]||[CLLocationManager authorizationStatus]!=kCLAuthorizationStatusAuthorizedWhenInUse){
//        [_locationManager requestWhenInUseAuthorization];
//
//    }
    
    //用户位置追踪(用户位置追踪用于标记用户当前位置，此时会调用定位服务)
//    self._mapView.userTrackingMode=MKUserTrackingModeFollow;
//    //设置地图类型
//    self._mapView.mapType=MKMapTypeStandard;
//    self._mapView.showsUserLocation = YES;
//    //设置定位精度
//    _locationManager.desiredAccuracy=kCLLocationAccuracyBestForNavigation;
//    //定位频率,每隔多少米定位一次
//    CLLocationDistance distance=20.0;//十米定位一次
//    _locationManager.distanceFilter=distance;
//

    //遮罩层
    MaskView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.size.width, self.view.size.height)];
    MaskView.backgroundColor = [UIColor blackColor];
    MaskView.alpha = 0;
    [self.view insertSubview:MaskView atIndex:2];
    //添加收侧滑手势
    UITapGestureRecognizer *tap =  [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
    [MaskView addGestureRecognizer:tap];
    MaskView.userInteractionEnabled = YES;
    ////    启动跟踪定位
//    [_locationManager startUpdatingLocation];

    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        //添加大头针
        [self requestURLwithViewForMap];

    });


}


#pragma mark -- CLLocationManagerDelegate

#pragma mark - 地图控件代理方法
#pragma mark 更新用户位置，只要用户改变则调用此方法（包括第一次定位到用户位置）
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    



}



-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    //由于当前位置的标注也是一个大头针，所以此时需要判断，此代理方法返回nil使用默认大头针视图
    if ([annotation isKindOfClass:[KCAnnotation class]]) {
        static NSString *key1=@"AnnotationKey1";
        MKAnnotationView *annotationView=[self._mapView dequeueReusableAnnotationViewWithIdentifier:key1];

        //如果缓存池中不存在则新建
        if (!annotationView) {
            annotationView=[[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:key1];
            annotationView.canShowCallout=true;//允许交互点击
//          annotationView.animatesDrop = YES;
            annotationView.calloutOffset=CGPointMake(0, 0);//定义详情视图偏移量
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
            [button setBackgroundImage:[UIImage imageNamed:@"进入列表按钮"] forState:UIControlStateNormal];
            button.backgroundColor = [UIColor clearColor];
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            button.frame = CGRectMake(0, 0, 60, 50);
            [button addTarget:self action:@selector(menu) forControlEvents:UIControlEventTouchUpInside];
            annotationView.rightCalloutAccessoryView = button;
            
        }
        
        //修改大头针视图
        //重新设置此类大头针视图的大头针模型(因为有可能是从缓存池中取出来的，位置是放到缓存池时的位置)
        annotationView.annotation=annotation;
        annotationView.image=((KCAnnotation *)annotation).image;//设置大头针视图的图片

        return annotationView;
    }else {
        return nil;
    }
}

#pragma mark 选中标注的处理事件
-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
    //显示选中大头针偏移为中心
    [self._mapView setCenterCoordinate:view.annotation.coordinate animated:YES];
    
    
    
    
    //记录当前大头针坐标用于调用导航
    latitude =view.annotation.coordinate.latitude;
    longitude =view.annotation.coordinate.longitude;
    
    latitude1 = [NSString stringWithFormat:@"%f",view.annotation.coordinate.latitude];
    longitude1 =[NSString stringWithFormat:@"%f",view.annotation.coordinate.longitude];;
    
    NSLog(@"%@====%@",latitude1,longitude1);
    
    //显示导航View
    [UIView animateWithDuration:0.4  animations:^{
        CGRect btnFrame = Nview.frame;
        btnFrame.origin.y = 0;
        Nview.frame = btnFrame;
    }];
        //导航View的Title
    Nview.NavigationTitle.text = [NSString stringWithFormat:@"%@%@",view.annotation.title,view.annotation.subtitle];
    
    //添加侧滑tableview
    [Rview removeFromSuperview];
    Rview = [[NSBundle mainBundle]loadNibNamed:@"RightView" owner:self options:nil][0];
    Rview.frame = CGRectMake(self.view.size.width, 0, self.view.frame.size.width/2, self.view.size.height);
    [self.view addSubview:Rview];

    
    
}

#pragma mark 取消选中标注的处理事件
-(void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view
{
    NSLog(@"取消了标注");
    //收起导航Viwe和侧滑View
    [UIView animateWithDuration:0.4  animations:^{
        CGRect btnFrame = Nview.frame;
        btnFrame.origin.y = -50;
        Nview.frame = btnFrame;
        MaskView.alpha = 0;
        
        CGRect btnFrame1 = Rview.frame;
        btnFrame1.origin.x = self.view.size.width+Rview.size.width;
        Rview.frame = btnFrame1;
    }];
}


//定位个人位置显示，开启跟踪
- (IBAction)Reposition:(id)sender {
    
    CLLocationCoordinate2D coord = self._mapView.userLocation.coordinate;
    MKCoordinateSpan span = { 0.01, 0.01 };
    MKCoordinateRegion region = { coord, span };
    [self._mapView setRegion:region animated:YES];

}

/**
 * 添加新设备时重新请求地图所有大头针坐标
 */
- (void)requestURLwithViewForMap{
    
    
    parameterDic = @{@"token":[NSUD objectForKey:@"token"]};
    [MapViewModel requestWithUrlForMap:self andParam:parameterDic success:^(NSMutableArray *model) {
        
        [self.AnnotationAry removeAllObjects];
        MapModel *model1 =  [[MapModel alloc]init];
        
        NSMutableArray *scheduingAry = [MapModel mj_objectArrayWithKeyValuesArray:model];
        
        
        for (model1 in scheduingAry) {
            
            NSLog(@"%@",model1);

            CLLocationCoordinate2D location1=CLLocationCoordinate2DMake(model1.latitude.doubleValue,model1.longitude.doubleValue);

            
//            CLLocationCoordinate2D location1 = [JZLocationConverter wgs84ToGcj02:CLLocationCoordinate2DMake(model1.latitude.doubleValue,model1.longitude.doubleValue)];

            
            
            NSLog(@"大头针坐标%f === %f",model1.latitude.doubleValue,model1.longitude.doubleValue);


            
            //地理编码类
            CLGeocoder *geocoder = [[CLGeocoder alloc]init];
            //生成一个location
            CLLocation *location = [[CLLocation alloc]initWithLatitude:location1.latitude longitude:location1.longitude];
            [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
                if (error){
                    
                    
                    NSLog(@"反向地理编码失败,error==%@",error);
                
                }else{
                    annotation1=[[KCAnnotation alloc]init];
                    CLPlacemark *mark = [placemarks firstObject];
                    annotation1.title=[NSString stringWithFormat:@"%@%@%@",mark.country,mark.administrativeArea,mark.locality];
                    annotation1.subtitle=[NSString stringWithFormat:@"%@%@",mark.subLocality,mark.name];
                    annotation1.image = [UIImage imageNamed:@"在线标记"];
                    annotation1.coordinate=location1;
                    annotation1.imie = model1.imie;
                    
                    NSLog(@"反向地理编码,==%@=%@=%@=%@=%@=%@=%@=%@=%@=%@=%@=%@",mark.name,mark.thoroughfare,mark.subThoroughfare,mark.locality,mark.subLocality,mark.administrativeArea,mark.subAdministrativeArea,mark.postalCode,mark.ISOcountryCode,mark.country,mark.inlandWater,mark.ocean);

                    [self.AnnotationAry addObject:annotation1];
                    [self._mapView addAnnotations:self.AnnotationAry];
                }
                if (_firstDisplay == YES) {
                [self._mapView showAnnotations:self._mapView.annotations animated:YES];
                }
            }];
        }
        
        //添加导航View
        [Nview removeFromSuperview];
        Nview = [[NSBundle mainBundle]loadNibNamed:@"NavigationView" owner:self options:nil][0];
        Nview.frame = CGRectMake(10, -50, self.view.frame.size.width-20, 50);
        [Nview.NavigationButton addTarget:self action:@selector(NavigationButton:) forControlEvents:UIControlEventTouchUpInside];
        [self.view insertSubview:Nview atIndex:2];


    } failure:^(NSString *error) {
        
        [MBProgressHUD yty_showErrorWithTitle:nil detailsText:error toView:self.view];


    }];
    
}


//调用系统导航
-(void)NavigationButton:(UIButton *)button
{
    
    UIAlertController* alerController = [UIAlertController alertControllerWithTitle:@"导航" message:nil preferredStyle:UIAlertControllerStyleActionSheet];

    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消"style:UIAlertActionStyleCancel handler:nil];
      UIAlertAction* gaodeMapAction = [UIAlertAction actionWithTitle:@"高德地图" style:UIAlertActionStyleDefault
        handler:^(UIAlertAction* _Nonnull action) {
            
            

            NSString * urlstring = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication= &backScheme=&lat=%f&lon=%f&dev=0&style=2",latitude,longitude] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

            
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlstring]];
                                                               
    }];
    
    UIAlertAction* baiduMapAction = [UIAlertAction actionWithTitle:@"百度地图" style:UIAlertActionStyleDefault
            handler:^(UIAlertAction* _Nonnull action) {

    NSString * urlstring = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=目的地&mode=driving&coord_type=gcj02",latitude,longitude] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];


                
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlstring]];
    }];
    
    UIAlertAction* ownMapAction = [UIAlertAction actionWithTitle:@"自带地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction* _Nonnull action) {
                                                             
    CLLocation *location = [[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
    _geocoder=[[CLGeocoder alloc]init];
//    注意地理编码一次只能定位到一个位置，不能同时定位，所在放到第一个位置定位完成回调函数中再次定位
    [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
                    if (error){
                        NSLog(@"反向地理编码失败,error==%@",error);
                    }else{
                        CLPlacemark *clPlacemark2=[placemarks firstObject];//获取第一个地标
                        MKPlacemark *mkPlacemark2=[[MKPlacemark alloc]initWithPlacemark:clPlacemark2];
                        NSDictionary *options=@{MKLaunchOptionsMapTypeKey:@(MKMapTypeStandard),MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving};
                        MKMapItem *mapItem1=[MKMapItem mapItemForCurrentLocation];//当前位置
                        MKMapItem *mapItem2=[[MKMapItem alloc]initWithPlacemark:mkPlacemark2];
                        [MKMapItem openMapsWithItems:@[mapItem1,mapItem2] launchOptions:options];
                    }
                                                                 
            }];
        
    }];
    
        [alerController addAction:cancelAction];
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://map/"]]) {
        [alerController addAction:baiduMapAction];
    }
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
        [alerController addAction:gaodeMapAction];
    };

    [alerController addAction:ownMapAction];
    if (objc_getClass("UIAlertController") != nil) {
        [self presentViewController:alerController animated:YES completion:nil];
    }
    
}

//开启侧滑
-(void)menu{
    [UIView animateWithDuration:0.4  animations:^{
        MaskView.alpha = 0.5;
        CGRect btnFrame = Rview.frame;
        btnFrame.origin.x = self.view.size.width/2;
        Rview.frame = btnFrame;
    }];
    
    
    
    
    //请求大头针设备列表
    [Rview requestURLwithViewForMapRightList:[NSString stringWithFormat:@"%f",latitude] An:[NSString stringWithFormat:@"%f",longitude]];
    
    
}

//收侧滑
-(void)tap{
    [UIView animateWithDuration:0.4 animations:^{
        MaskView.alpha = 0;
        CGRect btnFrame = Rview.frame;
        btnFrame.origin.x = self.view.size.width+Rview.size.width;
        Rview.frame = btnFrame;
    }];
}


-(NSMutableArray *)AnnotationAry
{
    if (!_AnnotationAry) {
        _AnnotationAry = [[NSMutableArray alloc]init];
    }
    return _AnnotationAry;
}



- (void)deleteAll
{
    //删除地图上所有的大头针
    [self._mapView removeAnnotations:self._mapView.annotations];
}






@end
